/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* MpmProjectTeamTypeService
* 项目组分类
*
* 修改纪录
* 2021-08-09 版本：1.0 mengmeng 创建。
* @version 版本：1.0
* @author 作者：mengmeng
* 创建日期：2021-08-09
*/
package com.topscomm.mpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.MpmProjectAppointmentEntity;
import com.topscomm.mpm.pojo.MpmProjectTeamEntity;
import com.topscomm.mpm.pojo.MpmProjectTeamTypeEntity;
import com.topscomm.mpm.utils.ConvertNumUtil;
import com.topscomm.mpm.utils.ConvertTimeUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mpm.service.IMpmProjectTeamTypeService;
import com.topscomm.mpm.service.impl.auto.MpmProjectTeamTypeServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(value = "mpmProjectTeamTypeService")
@Scope(value = "singleton")
public class MpmProjectTeamTypeService extends MpmProjectTeamTypeServiceAuto implements IMpmProjectTeamTypeService {

    @Autowired
    private MpmProjectTeamService mpmProjectTeamService;
    /**
     * @Description:    插入团队类型
     * @Author:         mengmeng
     * @Date:           2021/8/9 16:32
     * @Version:        1.0
     */
    @Override
    @Transactional
    public MpmProjectTeamTypeEntity insertTeamType(String projectCode, Long appointmentId) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" {0} = '{1}' and {2} = {3}", MpmProjectTeamTypeEntity.FieldProjectcode, projectCode, MpmProjectTeamTypeEntity.FieldAppointmentid, appointmentId);
        int count = this.getCount(sql.toString());
        if (count > 0) {
            return null;
        }
        MpmProjectTeamTypeEntity entity = new MpmProjectTeamTypeEntity();
        entity.setAppointmentid(appointmentId);
        entity.setProjectcode(projectCode);
        entity.setTeamname("项目核心组");
        entity.setAppointmenttype(MpmSystemConst.MpmTeamTypeAppointment.appointment);
        return this.insert(entity);
    }

    /**
    * @Description:    根据任命书id查询
    * @Author:         mengmeng
    * @Date:           2021/8/28 16:24
    * @Version:        1.0
    */
    @Override
    public List<MpmProjectTeamTypeEntity> queryByAppointmentId(String appointmentId) {
        if (StringUtil.isEmpty(appointmentId)) {
            return new ArrayList<>();
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" appointmentid = '{0}'", appointmentId);
        sql.appendSingle(" order by createon desc ");
        return this.queryByWhere(sql.toString());
    }

    @Override
    protected void beforeInsert(BasicEntity entity) throws ServiceException {
//        List<MpmProjectTeamTypeEntity> teamTypeList = queryByAppointmentId(ConvertUtil.convertToString(entity.getValue(MpmProjectTeamTypeEntity.FieldAppointmentid)));
//        for (MpmProjectTeamTypeEntity teamTypeEntity : teamTypeList) {
//            if (teamTypeEntity.getValue(MpmProjectTeamTypeEntity.FieldTeamname).equals(entity.getValue(MpmProjectTeamTypeEntity.FieldTeamname))) {
//                throw new ServiceException("工作组名称不能重复！");
//            }
//        }
    }
    /**
     * @Description:    生成三个组（业务、标前引导、标书）
     * @Author:         houyuhang
     * @Date:           2022/7/12
     */
    @Transactional
    public List<BasicEntity> insertGenGroup(String projectCode, Long appointmentId) {
        List<BasicEntity> basicEntities = new ArrayList<>();
        basicEntities.add(insertTemplate(projectCode, appointmentId, MpmSystemConst.TemplateGroup.TemplateGroupThree,3));
        basicEntities.add(insertTemplate(projectCode, appointmentId, MpmSystemConst.TemplateGroup.TemplateGroupTwo,2));
        basicEntities.add(insertTemplate(projectCode, appointmentId, MpmSystemConst.TemplateGroup.TemplateGroupOne,1));
        return basicEntities;
    }
    /**
     * @Description:    生成工作组模板
     * @Author:         houyuhang
     * @Date:           2022/7/12
     */
    public MpmProjectTeamTypeEntity insertTemplate(String projectCode, Long appointmentId,String teamName,int groupType) {
        MpmProjectTeamTypeEntity entity = new MpmProjectTeamTypeEntity();
        entity.setAppointmentid(appointmentId);
        entity.setProjectcode(projectCode);
        entity.setTeamname(teamName);
        entity.setGrouptype(groupType);
        entity.setAppointmenttype(MpmSystemConst.MpmTeamTypeAppointment.appointment);
        return entity;
    }
    /**
     * @Description:    新增模板工作组
     * @Author:         houyuhang
     * @Date:           2022/7/13
     */
    @Transactional
    public Map<String, Object> addTemplateGroup(Map<String, Object> paraMap) {
        // 转换为MpmProjectTeamTypeEntity对象
        MpmProjectTeamTypeEntity mpmProjectTeamTypeEntity = new MpmProjectTeamTypeEntity();
        mpmProjectTeamTypeEntity.convertFromMap(paraMap);
        // 查询有几个相同的模板工作组
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" appointmentid = '{0}' and grouptype = '{1}' ", mpmProjectTeamTypeEntity.getAppointmentid(), mpmProjectTeamTypeEntity.getGrouptype());
        List<MpmProjectTeamTypeEntity> typeEntities = this.queryByWhere(sql.toString());
        String tempStr = "";
        if (!CollectionUtil.isEmpty(typeEntities)) {
            int length = typeEntities.size() + 1;
            String lengthStr = ConvertNumUtil.trans(length);
            int grouptype = mpmProjectTeamTypeEntity.getGrouptype();
            if (grouptype == 3) {
                tempStr = MpmSystemConst.TemplateGroup.TemplateGroupThree;
            } else if (grouptype == 2) {
                tempStr = MpmSystemConst.TemplateGroup.TemplateGroupTwo;
            }
            mpmProjectTeamTypeEntity.setTeamname(tempStr + "（" + lengthStr + "组）");
        }
        mpmProjectTeamTypeEntity = this.insert(mpmProjectTeamTypeEntity);
        // 如果只有一个相同的模板工作组，前一个改为(一组)
        if (!CollectionUtil.isEmpty(typeEntities) && typeEntities.size() == 1) {
            MpmProjectTeamTypeEntity firstEntity = typeEntities.get(0);
            firstEntity.setTeamname(tempStr + "（一组）");
            this.updateEntity(firstEntity);
        }
        return mpmProjectTeamTypeEntity.convertToMap();
    }
    /**
     * @Description:    删除项目组时，如果模板项目组删除前只有两个，将未删除的项目组进行重命名
     * @Author:         houyuhang
     * @Date:           2022/7/14
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    protected void deleteBefore(String whereSql) {
        super.deleteBefore(whereSql);
        // 找到这个项目组
        List<MpmProjectTeamTypeEntity> mpmProjectTeamTypeEntities = this.queryByWhere(whereSql);
        if (mpmProjectTeamTypeEntities.size() == 0) {
            return;
        }
        MpmProjectTeamTypeEntity entity = mpmProjectTeamTypeEntities.get(0);
        // 删除项目组同步删除项目组成员
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" teamid = '{0}' ", entity.getId());
        mpmProjectTeamService.deleteByWhere(sql.toString());
        // 删除工作组时模板工作组改名
        this.changeNameTemplateTeamType(entity);
    }
    /**
     * @Description:    撤销工作组/恢复撤销工作组
     * @Author:         houyuhang
     * @Date:           2023/03/29
     */
    @Transactional
    public String revokeTeamType(Map<String, Object> paraMap) {
        // 撤销工作组/取消撤销工作组
        Map<String, Object> teamTypeMap = new HashMap<>();
        teamTypeMap.put("id", ConvertUtil.convertToString(paraMap.get("id")));
        teamTypeMap.put("appointmenttype", ConvertUtil.convertToString(paraMap.get("appointmenttype")));
        this.update(teamTypeMap);
        // 撤销/取消撤销工作组成员
        Map<String, Object> teamMap = new HashMap<>();
        // 获取工作组下所有成员
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled = 1 and teamid = '{0}' ", ConvertUtil.convertToString(paraMap.get("id")));
        List<MpmProjectTeamEntity> teamEntities = mpmProjectTeamService.queryByWhere(sql.toString());
        if (CollectionUtil.isEmpty(teamEntities)) {
            return ConvertUtil.convertToString(paraMap.get("appointmenttype"));
        }
        String ids = teamEntities.stream().map(item -> ConvertUtil.convertToString(item.getId())).collect(Collectors.joining(","));
        teamMap.put("ids", ids);
        if (MpmSystemConst.MpmTeamTypeAppointment.revoke.equals(ConvertUtil.convertToString(paraMap.get("appointmenttype")))) {
            mpmProjectTeamService.insertRevoke(teamMap);
        } else if (MpmSystemConst.MpmTeamTypeAppointment.appointment.equals(ConvertUtil.convertToString(paraMap.get("appointmenttype")))) {
            mpmProjectTeamService.deleteRevoke(teamMap);
        }
        return ConvertUtil.convertToString(paraMap.get("appointmenttype"));
    }
    /**
     * @Description:    删除工作组时模板工作组改名
     * @Author:         houyuhang
     * @Date:           2023/04/10
     */
    public void changeNameTemplateTeamType(MpmProjectTeamTypeEntity entity) {
        // 如果不是业务工作组，标前引导工作组，不需要重命名
        if (entity.getGrouptype() < 2) {
            return;
        }
        // 查找同类型项目组
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" appointmentid = '{0}' and grouptype = '{1}' and id != '{2}' ", entity.getAppointmentid(), entity.getGrouptype(), entity.getId());
        List<MpmProjectTeamTypeEntity> mpmProjectTeamTypeEntities2 = this.queryByWhere(sql.toString());
        if (mpmProjectTeamTypeEntities2.size() != 1) {
            return;
        }
        // 如果只存在一个同类型项目组,将项目组名称改为默认
        MpmProjectTeamTypeEntity updateEntity = mpmProjectTeamTypeEntities2.get(0);
        String temp = "";
        int grouptype = updateEntity.getGrouptype();
        if (grouptype == 3) {
            temp = MpmSystemConst.TemplateGroup.TemplateGroupThree;
        } else if (grouptype == 2) {
            temp = MpmSystemConst.TemplateGroup.TemplateGroupTwo;
        }
        updateEntity.setTeamname(temp);
        this.updateEntity(updateEntity);
    }
}
